import { SUCCESS_CODE } from '@/utils/request';
import { UploadOutlined } from '@ant-design/icons';
import {
  ProForm,
  // ProFormDateRangePicker,
  ProFormText,
} from '@ant-design/pro-components';

import type { FormInstance } from 'antd';
import { Button, Form, message, Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile, UploadProps } from 'antd/lib/upload/interface';
import { useRef, useState } from 'react';
import { updateAcitvity } from '../service';
import styles from '../style.less';
import type { activityItem, updateactivityItem } from '../types';

interface undateParkList {
  ruleData: activityItem;
  visible: boolean;
  unVisible: () => void;
  reloadFunc: () => void;
}

export default (props: undateParkList) => {
  const { visible, unVisible, ruleData, reloadFunc } = props;
  const [fileList, setFileList] = useState<UploadFile[]>([
    {
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: ruleData.picture,
    },
  ]);
  const formRef = useRef<FormInstance>();
  const onChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    if (file.status === 'done') {
      formRef?.current?.setFieldsValue({ picture: file.response.data.url });
      message.success(`${file.name} 图片上传成功`);
    } else if (file.status === 'error') {
      message.error(`${file.name} 图片上传失败`);
    }
    setFileList(newFileList);
  };

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  return (
    <div>
      <Modal
        onCancel={unVisible}
        centered
        visible={visible}
        title="更新活动"
        width={800}
        footer={null}
      >
        <ProForm<updateactivityItem>
          onFinish={async (values) => {
            const schemeId = ruleData.id;
            const hide = message.loading('正在提交');
            try {
              const res = await updateAcitvity(schemeId, values);
              hide();
              if (res.code === SUCCESS_CODE) {
                message.success('更新成功');
                unVisible();
                reloadFunc();
                return true;
              }
              message.error(`更新失败！${res.message}`);
              return false;
            } catch (error) {
              hide();
              message.error('更新失败！未知的错误！');
              return false;
            }
          }}
          formRef={formRef}
          className={styles.stepsaction}
        >
          <ProFormText
            width={'xl'}
            name="name"
            className={styles.stepsaction}
            label="活动名称"
            placeholder="请输入"
            rules={[{ required: true, message: '请输入活动名称' }]}
            initialValue={ruleData.name}
          />
          <ProFormText
            width={'xl'}
            name="links"
            className={styles.stepsaction}
            label="活动地址"
            placeholder="请输入"
            rules={[{ required: true, message: '请输入活动地址' }]}
            initialValue={ruleData.links}
          />
          <Form.Item
            name="picture"
            label="上传图片"
            // rules={[{  }]}
            style={{ width: 500, height: 200 }}
            initialValue={ruleData.picture}
          >
            <ImgCrop
              // grid
              rotate
              aspect={343 / 128}
              quality={1}
              beforeCrop={(file: File): Promise<boolean> =>
                new Promise<boolean>((resolve, rejects) => {
                  const { name } = file;
                  // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
                  const nameRegExp = new RegExp('(.jpeg|.png|.jpg)$');
                  const isImage = nameRegExp.test(name);
                  const isLt512kb = file.size / 1024 < 512;
                  if (!isImage) {
                    message.error({
                      content: '文件类型错误, 请上传一个图片文件,支持格式jp(e)g或png',
                      key: 'upload_image',
                    });
                    rejects();
                    return;
                  }
                  if (!isLt512kb) {
                    message.error({
                      content: '文件过大，请上传一个小于512kb的文件',
                      key: 'upload_image',
                    });
                    rejects();
                    return;
                  }
                  resolve(true);
                })
              }
            >
              <Upload
                action="/api/file/upload/singleImage"
                listType="picture-card"
                fileList={fileList}
                onChange={onChange}
                onPreview={onPreview}
                maxCount={1}
              >
                <Button icon={<UploadOutlined />} style={{ width: '106px', height: '106px' }}>
                  <div>
                    <a>点击上传图片</a>
                  </div>
                  <a> (343 * 128)</a>
                </Button>
              </Upload>
            </ImgCrop>
          </Form.Item>
        </ProForm>
      </Modal>
    </div>
  );
};
